'use strict';

exports.index = async ctx => {
  const { query } = ctx.request;
  let pageSize = 10;
  if (query.pageSize) pageSize = Number(query.pageSize);
  const where = {};
  const { status } = query;
  if (status)where.status = status;
  const options = {
    limit: pageSize,
    offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
    order: [
      [ 'order', 'DESC' ],
    ],
    raw: true,
    where,
  };
  const {
    count: total, rows: list,
  } = await ctx.model.Withdrawal.findAndCountAll(options);
  ctx.body = {
    list,
    pagination: {
      total,
      pageSize,
      current: parseInt(query.currentPage, 10) || 1,
    },
  };
};

exports.show = async ctx => {
  const withdrawal = await ctx.model.Withdrawal.findByPk(ctx.params.id);
  if (withdrawal) {
    ctx.body = withdrawal;
  } else {
    ctx.status = 404;
  }
};

exports.update = async ctx => {
  const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
  const { role } = currentUser;
  const withdrawal = await ctx.model.Withdrawal.findByPk(ctx.params.id);
  if (withdrawal) {
    ctx.validate({
      status: { type: 'enum', values: [ 'success' ], required: false },
    });
    const { status } = ctx.request.body;
    switch (role) {
      case 'admin':
        ctx.body = await withdrawal.update({ status });
        break;
      default:
    }

  } else {
    ctx.status = 404;
  }
};

exports.destroy = async ctx => {
  const withdrawal = await ctx.model.Withdrawal.findByPk(ctx.params.id);
  if (withdrawal) {
    await withdrawal.destroy();
    ctx.status = 204;
  } else {
    ctx.status = 404;
  }
};
